package GUI; //done

import java.awt.Rectangle;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import Client.ConnectionToServer;
import Entities.Customer;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

/**
 * This class controls the Customer Window.
 * @author ameer
 * @author waleed
 * @author bshara
 * @author kamil
 */
public class CustomerWindow extends JPanel{
	/** The serial Version UID. */
	private static final long serialVersionUID = 1L;

	/** The Customer Id Label. */
	private JLabel cIdLabel = null;
	
	/** The Customer Name Label. */
	private JLabel cNameLabel= null;
	
	/** The Customer Age Label. */
	private JLabel cAgeLabel= null;
	
	/** The Customer Area Label. */
	private JLabel cAddressLabel= null;
	
	/** The Customer Phone Label. */
	private JLabel cPhoneLabel= null;
	
	/** The Customer Importance. */
	private JLabel cImportance = null;
	
	/** The Customer ID Text Field. */
	private JTextField cIdTextField = null;
	
	/** The Customer Name Text Field. */
	private JTextField cNameTextField = null;
	
	/** The Customer Age Text Field. */
	private JTextField cAgeTextField = null;
	
	/** The Customer Address JComboBox. */
	private JComboBox custAddressJComboBox= null;
	
	/** The Customer Address Text Field. */
	private JTextField cAddresstextField;
	
	/** The Customer Phone Text Field. */
	private JTextField cPhoneTextField= null;
	
	/** The Customer Importance Text Field. */
	private JTextField cImportanceTextField= null;
	
	/** The Save Button. */
	private JButton saveButton = null;
	
	/** The Cancel Button. */
	private JButton cancelButton = null;
	
	/** The Update Button. */
	private JButton updateButton = null;
	
	/** The Category JComboBox. */
	private JComboBox categoryJComboBox= null;
	
	/** The Category Product Text Area. */
	private JTextArea categoryProductTextArea = null;

	/** The Customer. */
	private Customer customer = null;
	
	/** The Background Label. */
	private JLabel BackgroundLabel;	
	
	/**
	 * The default constructor
	 */
	public CustomerWindow() {
		super();
		initialize();	
	}
	
	/**
	 * This function initializes CustomerWindow
	 */
	private void initialize() {
		cIdLabel = new JLabel();
		cIdLabel.setBounds(new Rectangle(15, 20, 130, 22));
		cIdLabel.setText("Customer ID:");
		
		cNameLabel = new JLabel();
		cNameLabel.setBounds(new Rectangle(15, 53, 130, 22));
		cNameLabel.setText("Customer name:");
		
		cAgeLabel = new JLabel();
		cAgeLabel.setBounds(new Rectangle(15, 146, 130, 22));
		cAgeLabel.setText("Customer age:");
		
		cAddressLabel = new JLabel();
		cAddressLabel.setBounds(new Rectangle(15, 83, 130, 22));
		cAddressLabel.setText("Customer address:");
		
		cPhoneLabel = new JLabel();
		cPhoneLabel.setBounds(new Rectangle(15, 113, 130, 22));
		cPhoneLabel.setText("Customer phone");
		
		cImportance = new JLabel();
		cImportance.setBounds(new Rectangle(15, 179, 130, 22));
		cImportance.setText("Customer importance");
		
		customer = new Customer(0,"", 0, 0,"");
		
		this.setSize(318, 321);
		this.setLayout(null);
		this.add(cIdLabel, null);
		this.add(cNameLabel, null);
		this.add(cAgeLabel, null);
		this.add(cAddressLabel, null);
		this.add(cPhoneLabel,null);
		this.add(cImportance,null);
		this.add(getCIdTextField(), null);
		this.add(getCNameTextField(), null);
		this.add(getCAageTextField(), null);
		this.add(getCustAddressJComboBox(), null);
		this.add(getCPhoneTextField(),null);
		this.add(getCImportanceTextField(),null);
		this.add(getCancelButton(),null);
		this.add(getCAddresstextField());
	}
	
	/**
	 * This function initializes cIdTextField	
	 */
	private JTextField getCIdTextField(){
		if (cIdTextField == null) {
			cIdTextField = new JTextField();
			cIdTextField.setBounds(new Rectangle(150, 20, 127, 25));
		}
		return cIdTextField;
	}
	
	/**
	 * This function initializes cNameTextField	
	 */
	private JTextField getCNameTextField(){
		if (cNameTextField == null) {
			cNameTextField = new JTextField();
			cNameTextField.setBounds(new Rectangle(150, 53, 127, 25));
		}
		return cNameTextField;
	}
	
	/**
	 * This function initializes cIdTextField	
	 */
	private JTextField getCAddresstextField(){
		if (cAddresstextField == null) {
			cAddresstextField = new JTextField();
			cAddresstextField.setBounds(150, 83, 31, 23);
			cAddresstextField.setColumns(10);
		}
		return cAddresstextField;
	}
	
	/**
	 * This function initializes cAgeTextField	
	 */
	private JTextField getCAageTextField(){
		if (cAgeTextField == null) {
			cAgeTextField = new JTextField();
			cAgeTextField.setBounds(new Rectangle(150, 146, 127, 25));
		}
		return cAgeTextField;
	}
	
	/**
	 * This function initializes cAreaTextField	
	 */
	private JComboBox getCustAddressJComboBox(){
		if (custAddressJComboBox == null) {
			custAddressJComboBox = new JComboBox();
			custAddressJComboBox.setBounds(new Rectangle(181, 82, 127, 25));
			String[] areaList = null;
			try{
				ConnectionToServer connectiontoserver = new ConnectionToServer();		
				areaList = (String[]) connectiontoserver.loadAllAddressZones();
				if (areaList == null){
					JOptionPane.showMessageDialog(null, "ERROR!!!");
					custAddressJComboBox.addItem(" ");
				}	
				else{
					int len = areaList.length;
					if (len == 0)
						custAddressJComboBox.addItem("0:EMPTY");	
					else
						custAddressJComboBox.addItem(" ");
					for(int i=0; i < len; i++){
						custAddressJComboBox.addItem(areaList[i]);
					}	
				}
			}
			catch(Exception e){
				JOptionPane.showMessageDialog(null, "ERROR!!!");
				custAddressJComboBox.addItem(" ");
			}
			custAddressJComboBox.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {	
				}	
			});	
		}
		return custAddressJComboBox;
	}
	
	/**
	 * This function initializes cPhoneTextField	
	 */
	private JTextField getCPhoneTextField(){
		if (cPhoneTextField == null) {
			cPhoneTextField = new JTextField();
			cPhoneTextField.setBounds(new Rectangle(150, 113, 127, 25));
		}
		return cPhoneTextField;
	}
	
	/**
	 * This function initializes cImportanceTextField	
	 */
	private JTextField getCImportanceTextField(){
		if (cImportanceTextField == null) {
			cImportanceTextField = new JTextField();
			cImportanceTextField.setBounds(new Rectangle(150, 179, 127, 25));
			cImportanceTextField.setEditable(false);
		}
		return cImportanceTextField;
	}
	
	/**
	 * This function initializes cancelButton
	 */	
	public JButton getCancelButton(){
		if (cancelButton == null){
			cancelButton = new JButton();
			cancelButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
				}
			});
			cancelButton.setText("Cancel");
			cancelButton.setBounds(new Rectangle(15, 258, 120, 29));
		}	
		return cancelButton;				
	}
	
	/**
	 * This function initializes SaveButton	
	 */
	private JButton getSaveButton() {
		if (saveButton == null) {
			saveButton = new JButton();
			saveButton.setBounds(new Rectangle(150, 220, 120, 29));
			saveButton.setText("Save");
			saveButton.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					String stready = updateCustomer();
					if (stready.equals("Ready")){
						try{
							ConnectionToServer connectiontoserver = new ConnectionToServer();
							String msgfromserver = (String)connectiontoserver.addCustomer(customer);
							String[] sectionList = (String[]) connectiontoserver.loadAllCategories();
							int CategoryID;
							int len = sectionList.length;
							if(len != 0){
								for(int i = 0; i < len ; i++){
									CategoryID = Integer.parseInt(sectionList[i].substring(0, sectionList[i].indexOf(":")));
									try{
										ConnectionToServer connectiontoserver2 = new ConnectionToServer();
										String msgfromserver2 = (String)connectiontoserver2.AddCustomerInterest(customer.getCustID(), CategoryID, 1);
										if (msgfromserver2 == null)
											JOptionPane.showMessageDialog(null, "Error, Can't add interest!");
									}
									catch(Exception e1){
										JOptionPane.showMessageDialog(null, "Error, Can't add Customer Interests!");
									}
								}
							}
							if (msgfromserver != null){
								if (msgfromserver.equals("OK")){
									JOptionPane.showMessageDialog(null, "The customer successfully saved");
									JFrame addCustomerInterestFrame = new JFrame();
									AddCustomerInterestWindow addCustomerInterestWindow = new AddCustomerInterestWindow();
									addCustomerInterestWindow.loadCustomer(customer);
									addCustomerInterestFrame.setSize(450, 600);
									addCustomerInterestFrame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
									addCustomerInterestFrame.setContentPane(addCustomerInterestWindow);
									addCustomerInterestFrame.setTitle("Add Customer Interests");
									addCustomerInterestFrame.setVisible(true);
								}
								
							}
							else
								JOptionPane.showMessageDialog(null, "FATAL ERROR");
						}
						catch (Exception excp){
							JOptionPane.showMessageDialog(null, "ERROR");	
						}	
					}					
				}				
			});						
		}
		return saveButton;
	}
	
	/**
	 * This function update customer to data from the form
	 */
	private String  updateCustomer(){
		try {
			long id = Long.parseLong(cIdTextField.getText());
			String customername= cNameTextField.getText();
			int age = Integer.parseInt((cAgeTextField.getText()));
			String areastr = (String)custAddressJComboBox.getSelectedItem();
			int  area = Integer.parseInt(areastr.substring(0, areastr.indexOf(":")));
			String phone = cPhoneTextField.getText();
			if (id >0 &&  !customername.equals("") && age > 0 && area >= 0 && !phone.equals("")){
				customer.setCustID(id);
				customer.setCustName(customername);
				customer.setCustAge(age);
				customer.setCustAddressZone(area);
				customer.setCustPhone(phone);
				return "Ready";
			}							
			else{
				JOptionPane.showMessageDialog(null, "Requested fields not filled");
				return "ERROR";
			}			
		}
		catch (Exception excp){
			JOptionPane.showMessageDialog(null, "ILEGAL INPUT");
			return "ERROR";
		}	
	}
	
	/**
	 * This function initializes updateButton	
	 */
	private JButton getUpdateButton() {
		if (updateButton == null) {
			updateButton = new JButton();
			updateButton.setBounds(new Rectangle(150, 220, 120, 29));
			updateButton.setText("Update");
			updateButton.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					String stready = updateCustomer();
					if (stready.equals("Ready")){
						try{
							ConnectionToServer connectiontoserver = new ConnectionToServer();
							String msgfromserver = (String)connectiontoserver.updateCustomer(customer);
							if (msgfromserver != null){
								if (msgfromserver.equals("OK"))
									JOptionPane.showMessageDialog(null, "The customer successfully update");
								else
									JOptionPane.showMessageDialog(null, "The customer not update!!!","WARNING", JOptionPane.WARNING_MESSAGE);
							}
							else
								JOptionPane.showMessageDialog(null, "ERROR!!!","CCRM ERROR",JOptionPane.ERROR_MESSAGE);
						}
						catch (Exception excp){
							JOptionPane.showMessageDialog(null, "FATAL ERROR!!!","CCRM ERROR",JOptionPane.ERROR_MESSAGE);
						}	
					}		
				}					
			});						
		}
		return updateButton;
	}
	
	/**
	 * This function load customer details to the form 
	 * @param customer
	 */
	public void loadCustomer(Customer customer){
		this.customer = customer;
		cIdTextField.setText(String.valueOf(customer.getCustID()));
		cNameTextField.setText(customer.getCustName()) ;
		cAgeTextField.setText(String.valueOf(customer.getCustAge()));
		cAddresstextField.setText(String.valueOf(customer.getCustAddressZone()));
		custAddressJComboBox.setSelectedItem(customer.getCustAddressZone());
		cPhoneTextField.setText(customer.getCustPhone()) ;
		cImportanceTextField.setText(String.valueOf(customer.getImportance()));		
	}
	
	/**
	 * This function initializes categoryJComboBox	
	 */
	private JComboBox getCategoryJComboBox(){
		if (categoryJComboBox == null) {
			categoryJComboBox = new JComboBox();
			categoryJComboBox.setBounds(new Rectangle(150, 230, 127, 25));
			String[] sectionList = null;
			try{
				ConnectionToServer connectiontoserver = new ConnectionToServer();		
				sectionList = (String[]) connectiontoserver.loadAllCategories();
				if (sectionList == null){
					JOptionPane.showMessageDialog(null, "ERROR!!!");
					categoryJComboBox.addItem(" ");
				}	
				else{
					int len = sectionList.length;
					if (len == 0)
						categoryJComboBox.addItem("0:EMPTY");
					else
						categoryJComboBox.addItem(" ");
					for(int i=0; i < len; i++){
						categoryJComboBox.addItem(sectionList[i]);
					}	
				}
			}
			catch(Exception e){
				JOptionPane.showMessageDialog(null, "ERROR!!!");
				categoryJComboBox.addItem(" ");
			}
			categoryJComboBox.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					String[] productList = null;
					try{
						String sectionId = (String)categoryJComboBox.getSelectedItem();
						int  sID = Integer.parseInt(sectionId.substring(0, sectionId.indexOf(":")));
						ConnectionToServer connectiontoserver = new ConnectionToServer();
						productList = (String[])connectiontoserver.loadCategoryProducts(sID);						
					}
					catch(Exception exc){
						JOptionPane.showMessageDialog(null, "FATAL ERROR!!!","",JOptionPane.ERROR_MESSAGE);
						categoryProductTextArea.setText("EMPTY!!!");
						return;
					}
					if (productList != null){	
						int len = productList.length, i=0;
						String str = "";
						for(i=0; i < len;i++){
							str = str+productList[i]+"\n";									
						}
						categoryProductTextArea.setText(str);					
					}
					else
						JOptionPane.showMessageDialog(null, "ERROR!!!","",JOptionPane.ERROR_MESSAGE);
				}	
			});	
		}
		return categoryJComboBox;
	}
	
	/**
	 * This function initializes categoryProductTextArea	
	 */
	private JTextArea getCategoryProductTextArea(){
		if (categoryProductTextArea == null) {
			categoryProductTextArea = new JTextArea();
			categoryProductTextArea.setBounds(new Rectangle(150, 290, 230, 80));
			categoryProductTextArea.setEditable(false);
		}
		return categoryProductTextArea;
	}
	
	/**
	 * This function add SaveButton to CustomerWindow
	 */
	public void addSaveButton(){
		this.add(getSaveButton(), null);
		cImportanceTextField.setText("1");
		cancelButton.setBounds(15, 220, 120, 29);
		BackgroundLabel = new JLabel("BackGround");
		BackgroundLabel.setIcon(new ImageIcon(AddCustomerInterestWindow.class.getResource("/Pictures/bg.png")));
		BackgroundLabel.setBounds(0, 0, 350, 321);
		this.add(BackgroundLabel);		
	}
	
	/**
	 * This function add UpdateButton to CustomerWindow
	 */
	public void addUpdateButton(){
		this.add(getUpdateButton(),null);
		cIdTextField.setEditable(false);
		cancelButton.setBounds(15, 220, 120, 29);
		BackgroundLabel = new JLabel("BackGround");
		BackgroundLabel.setIcon(new ImageIcon(AddCustomerInterestWindow.class.getResource("/Pictures/bg.png")));
		BackgroundLabel.setBounds(0, 0, 350, 321);
		this.add(BackgroundLabel);		
	}
}
